# coding:utf-8
import os
import time
from multiprocessing import Process

os.environ["PATH"] = os.path.dirname(__file__) + os.pathsep + os.environ["PATH"]
# os.environ["PATH"] = r'D:\pv\audio\Lib\site-packages' + os.pathsep + os.environ["PATH"]
import mpv

player = mpv.MPV()

# OGG_OPUS_FILE = r'D:\dl\audios\x.opus'
OGG_OPUS_FILE = r"path-to-audio.opus"


def use_mpv():
    # player = mpv.MPV(ytdl=True)
    player.play(OGG_OPUS_FILE)
    player.wait_for_playback()


@player.python_stream('foo')
def reader():
    parts_total = 25
    parts_played = 0
    with open(OGG_OPUS_FILE, 'rb') as f:
        while parts_played < parts_total:
            # time.sleep(3)
            parts_played += 1
            print(parts_played)
            yield f.read(1024)


def mpv_stream():
    player.play('python://foo')
    player.wait_for_playback()
    print('after wait_for_playback')


def run_mpv():
    # use_mpv()

    # mpv_stream()
    p = Process(target=mpv_stream)
    p.start()
    # p.join()


current_frame = 0

def run_sounddevice():
    #https://python-sounddevice.readthedocs.io/en/0.4.6/examples.html
    import threading

    import sounddevice as sd
    import soundfile as sf
    event = threading.Event()
    try:
        data, fs = sf.read(OGG_OPUS_FILE, always_2d=True)


        def callback(outdata, frames, time, status):
            global current_frame
            if status:
                print(status)
            chunksize = min(len(data) - current_frame, frames)
            outdata[:chunksize] = data[current_frame:current_frame + chunksize]
            if chunksize < frames:
                outdata[chunksize:] = 0
                raise sd.CallbackStop()
            current_frame += chunksize

        stream = sd.OutputStream(
            samplerate=fs,  channels=data.shape[1],
            callback=callback, finished_callback=event.set)
        #device=args.device,
        with stream:
            event.wait()  # Wait until playback is finished

    except Exception as e:
        print(str(e))
if __name__ == "__main__":
    print('start main')
    run_mpv()
    # run_sounddevice()
    print('end main')
